<template>
	<view class="container select">
		<!-- <view class="back_img">
	  	 <image class="image" src="/static/images/qpbc.png" mode="widthFix"></image>
	  </view> -->
		<view class="wechatapp">
			<!-- <view class="header">
        <image class="image" :src="imgurl+loginBackdropImg" mode="widthFix"></image>
      </view> -->
			<view class="logoname1" v-if="form.longinType==1">
				请输入验证码
			</view>
			<view class="logoname" v-if="form.longinType==2">
				账号密码登录
			</view>
			<view class="logoname-js" v-if="form.longinType==1">
				验证码已发送至 {{form.mobile}}
			</view>
		</view>

		<!-- <view class="auth-phonetitle" v-if="form.longinType==2">请输入您的账号密码登录</view>
	<view class="auth-phonetitle" v-if="form.longinType==1">
		请输入您的手机号登录
	</view> -->
		<!-- <view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view> -->
		<view class="login-view">
			<u-form :model="form" ref="uForm" labelWidth="0">


				<u-form-item class="item-index" label-width="20" v-if="form.longinType==2" label=" " prop="userCode"
					:label-style="{'font-size': '30rpx','font-weight': 'bold'}">
					<u-input v-model="form.userCode" placeholder="请输入账号" :custom-style="{'font-size': '30rpx'}" />
				</u-form-item>
				<u-form-item v-if="form.longinType==2" label-width="20" label=" " prop="password"
					:label-style="{'font-size': '30rpx','font-weight': 'bold'}">
					<u-input v-model="form.password" type="password" :adjust-position="false" placeholder="请输入密码"
						:custom-style="{'font-size': '30rpx'}" />
				</u-form-item>
				<view class="index-sss">


					<u-form-item v-if="form.longinType==1" label-width="20" label=" "
						:label-style="{'font-size': '30rpx','font-weight': 'bold'}">
						<view style="width: 100%;text-align: center;">
							<!-- @finish="finish" -->
							<u-message-input :focus="true" :value="form.smsCode" :maxlength="6"
								@finish="finish"></u-message-input>
						</view>


					</u-form-item>
				</view>

			</u-form>
		</view>
		<view class="login-btn" v-if="form.longinType==1">
			<!-- @click="gocode"  disabled="disabled"-->
			<!-- <u-button class="btstyle"     :custom-style="{'width':'165rpx','background': '#C9C9C9','color':'#ffffff','border':'none'}" :disabled="disabled"></u-button> -->
			<u-button
				:custom-style="{'width':'100%','background': '#C9C9C9','color':'#ffffff','border':'none','height':'99rpx'}"
				@click="gocode" shape="circle" :disabled="disabled" class="button btn-normal"
				:class="!disabled?'u-btn-class':''">{{bttest}}</u-button>



		</view>

		<view class="login-btn" v-if="form.longinType==2">
			<!-- @click="gocode"  disabled="disabled"-->


			<u-button
				:custom-style="{'width':'100%','background': '#C9C9C9','color':'#ffffff','border':'none','height':'99rpx'}"
				shape="circle" @click="goregister" class="button btn-normal">登录</u-button>

		</view>
		<view class="login-btn-qk">
			<text @click="qhloginfun">{{form.longinType==1?"密码登录":"手机号登录"}}</text>
		</view>
		<!-- <view class="login-btn">
	  <u-button  shape="circle" @click="goregister"  class="button btn-normal">登录</u-button>
	
	</view> -->


		<!-- <view class="no-login-btn">
	  <u-button  shape="circle"   class="button btn-normal">暂不登录</u-button>
    </view> -->
		<!-- <view class="login-test">
		<view class="login-item">
			<view class="login-icom">
				<u-icon name="plus-circle" class="login-icoms" color="#000000" size="80"></u-icon>
			</view>
			
			<text class="login-text">注册</text>
		</view>
		<view class="login-item">
			<view class="login-icom">
				<u-icon name="lock-open" class="login-icoms" color="#000000" size="80"></u-icon>
			</view>
			
			<text class="login-text">忘记密码</text>
			
		</view>
		
	</view> -->
	</view>
</template>

<script>
	import {
		sendUserCode,
		userLogin
	} from "@/api/login/login";
	import {
		BASE_URL_IMAHE
	} from "../../../utils/https";
	const app = getApp();
	export default {
		data() {
			return {
				value: false,
				// 商城基本信息
				storeInfo: undefined,
				// 微信小程序登录凭证 (code)
				// 提交到后端，用于换取openid
				imgurl: BASE_URL_IMAHE,
				code: "",
				loginBackdropImg: "",
				form: {
					longinType: 1,
					mobile: '',
					smsCode: '',
					password: '',
					userCode: '',
					token: '',

				},
				list: [{
					name: "注册",
					checked: false,
					disabled: false,
				}, ],
				bttest: "重新获取短信验证码",
				disabled: false,
				times: 60,
				//定时器
				intetime: null,
				isfs: false,
				type: 0,
				mobile: '',
				
				rules: {
					// 字段名称
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					// smsCode: [{
					// 	required: true,
					// 	message: '请输入验证码',
					// 	trigger: ['change', 'blur'],
					// }],
					password: [{
						required: true,
						message: '请输入密码',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					userCode: [{
						required: true,
						message: '请输入账号',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],

				},
				islogins:false,
			};
		},

		created() {},
		beforeDestroy() {
			console.log("返回了");
			clearInterval(this.intetime)
			if (!uni.getStorageSync("userId")) {
				uni.removeStorageSync("userId");
				uni.removeStorageSync("mobile");
			}
		},
		onShow(){
			
			this.islogins=false
		},
		onLoad(e) {
			this.form.longinType = e.type

			if (e.type == 1) {

				this.form.mobile = e.phone
				this.getgocode()
			}
			this.loginBackdropImg = uni.getStorageSync('loginBackdropImg') ? uni.getStorageSync('loginBackdropImg') : ""
			var sjs = this.randomWord()
			var datatime = Date.parse(new Date());
			var tokens = '' + sjs + '' + datatime
			this.form.token = tokens
			this.form.v = uni.getStorageSync("v")


		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			finish(e) {
				if(this.islogins){
					return
				}else{
					this.islogins=true
				}
				this.goregister(e)
			},
			qhloginfun() {
				if (this.form.longinType == 1) {

					this.form.longinType = 2
				} else {
					uni.reLaunch({
						url: "/pages/empower/register"
					})
					// this.form.longinType=1
				}
				uni.setStorageSync("longinType", this.form.longinType)
			},
			randomWord() {
				var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
					'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
					'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
					'x', 'y', 'z'
				];
				var nums = "";
				for (var i = 0; i < 20; i++) {
					var id = parseInt(Math.random() * 61);
					nums += chars[id]
				}
				return nums;
			},
			async goregister(index) {
				// code:'',
				// password:'',
				// againPassword:'',
				this.form.smsCode = index
				console.log("console", index)
				let tjshow = true
				console.log(this.form)



				this.$refs.uForm.validate(valid => {
					if (valid) {
						tjshow = true
					} else {

						tjshow = false
					}
				});

				if (!tjshow) {
					return
				}
				var formdata = {};


				if (this.form.longinType == 1) {
					formdata.longinType = this.form.longinType
					formdata.mobile = this.form.mobile
					formdata.smsCode = this.form.smsCode
					formdata.token = this.form.token
				} else {
					formdata.longinType = this.form.longinType
					formdata.userCode = this.form.userCode
					formdata.password = this.form.password
					formdata.token = this.form.token

				}

				// #ifdef MP-WEIXIN
				formdata.v = uni.getStorageSync("v")
				// #endif
				let Registe = await userLogin(JSON.stringify(formdata))
				if (Registe.result == 0) {
					uni.showToast({
						title: "登录成功",
						icon: "success",
						duration: 2000,
					});
					let that = this
					// uni.setStorageSync("userId",Registe.user.id)
					if (this.form.longinType == 1) {
						uni.setStorageSync("userMobile", Registe.user.userMobile)
						uni.setStorageSync("userRef", Registe.user.userRef)
						uni.setStorageSync("userCode", Registe.user.userName)
						uni.setStorageSync("userOffice", Registe.user.userOffice)
						uni.setStorageSync("userId", Registe.user.id)
						uni.setStorageSync("userHead", Registe.user.userHead)
						uni.setStorageSync("userName", Registe.user.userName)




					} else {
						uni.setStorageSync("userMobile", Registe.user.userCode)
						uni.setStorageSync("userRef", Registe.user.userRef)
						uni.setStorageSync("userCode", Registe.user.userCode)
						uni.setStorageSync("userOffice", Registe.user.userOffice)
						uni.setStorageSync("userId", Registe.user.id)
						uni.setStorageSync("userHead", Registe.user.userHead)
						uni.setStorageSync("userName", Registe.user.userName)

					}



					// #ifdef MP-WEIXIN
					console.log("vvvvvvvvvv")
					uni.setStorageSync("v", Registe.v)
					console.log(uni.getStorageSync("v"), "vvvvvvvvvv")
					// #endif

					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/home/index"
						})
						this.islogins=false
					}, 1500);
					

				} else {
					var sjs = this.randomWord()
					var datatime = Date.parse(new Date());
					var tokens = '' + sjs + '' + datatime
					this.form.token = tokens
					uni.showToast({
						icon: "none",
						title: Registe.message
					})
					this.islogins=false
				}




			},
			async gocode() {
				let that = this
				if (this.form.mobile == "") {
					uni.showToast({
						icon: "none",
						title: "请填写手机号"
					})
					return
				}
				var data = {
					mobile: this.form.mobile,

				};
				let Code = await sendUserCode(JSON.stringify(data))

				if (Code.result == 0) {
					this.isfs = true
					this.bttest = "重新获取短信验证码(60\')"
					this.disabled = true
					that.times = 60
					that.intetime = setInterval(() => {
						that.times = that.times - 1
						that.bttest = "重新获取短信验证码(" + that.times + '\')'
						console.log(that.times)

						if (that.times <= 0) {
							this.isfs = false
							clearInterval(that.intetime)
							this.disabled = false
							this.bttest = "重新获取短信验证码"
						}
					}, 1000)
					uni.showToast({
						icon: "none",
						title: "验证码发送成功"
					})
				} else {
					uni.showToast({
						icon: "none",
						title: Code.message
					})
				}

			},
			getgocode() {
				let that = this
				if (this.form.mobile == "") {
					uni.showToast({
						icon: "none",
						title: "请填写手机号"
					})
					return
				}


				this.isfs = true
				this.bttest = "重新获取短信验证码(60\')"
				this.disabled = true
				that.times = 60
				that.intetime = setInterval(() => {
					that.times = that.times - 1
					that.bttest = "重新获取短信验证码(" + that.times + '\')'
					console.log(that.times)

					if (that.times <= 0) {
						this.isfs = false
						clearInterval(that.intetime)
						this.disabled = false
						this.bttest = "重新获取短信验证码"
					}
				}, 1000)

			},
			// 选中某个复选框时，由checkbox时触发
			checkboxChange(e) {
				console.log(e, "123");
				this.value = e.value;
				console.log(this.value, "value");
			},
			// 选中任一checkbox时，由checkbox-group触发
			checkboxGroupChange(e) {
				console.log(e, "345");
			},

			//用户登录凭证code
			getCode() {
				const than = this;
				return new Promise((resolve, reject) => {
					uni.login({
						provider: "weixin",
						success: (res) => {
							console.log(res.code, "res code");
							resolve(res.code);
						},
						fail: reject,
					});
				});
			},

			async getPhoneNumber(e) {
				console.log(e, "eee");
				console.log(e.detail.code, "e 手机code");
				const code = await this.getCode();
				console.log(code, "登录用得code");
				const app = this;
				if (e.detail.code) {
					const data = {
						phoneCode: e.detail.code,
						wxOpenIdCode: code,
						parentInviteCode: uni.getStorageSync("parentInviteCode") || "",
					};
					//登录接口
					const logoData = await wxLoginApi(data);
					console.log(logoData, "提交到后端登录接口");
					if (logoData.code === 0) {
						uni.showToast({
							title: "登录成功",
							icon: "success",
							duration: 2000,
						});
						// 获取到的当前数据存入缓存
						const {
							wxToken,
							openId,
							userInfo
						} = logoData.data;
						uni.setStorageSync("token", wxToken);
						uni.setStorageSync("openId", userInfo.wxOpenid);
						uni.setStorageSync("userInfoServer", userInfo);
						uni.setStorageSync("phoneNumber", userInfo.phone);
						uni.setStorageSync("userId", userInfo.userId);
						setTimeout(() => {
							app.handleCancel();
						}, 1500);
					} else {
						uni.showToast({
							title: "登录失败",
							icon: "success",
							duration: 2000,
						});
						setTimeout(() => {
							app.handleCancel();
						}, 1500);
					}
				}
			},

			// getUserProfile() {
			//   uni.showLoading({
			//     title: "加载中...",
			//   });
			//   //获取用户信息 包含appid
			//   // const appid = uni.getAccountInfoSync();
			//   // console.log(appid, "appid");
			//   const app = this;
			//   console.log("登录授权开始");
			//   wx.canIUse("getUserProfile") &&
			//     wx.getUserProfile({
			//       lang: "zh_CN",
			//       desc: "获取用户相关信息",
			//       async success(res) {
			//         console.log("用户同意了授权");
			//         console.log("用户信息:", res);
			//         // const { encryptedData, iv } = res;
			//         const {
			//           gender,
			//           avatarUrl,
			//           city,
			//           country,
			//           language,
			//           nickName,
			//           province,
			//         } = res.userInfo;
			//         uni.setStorageSync("MyUserInfo", res.userInfo);
			//         // const code = await app.getCode();
			//         uni.login({
			//           provider: "weixin",
			//           success: async (codeData) => {
			//             // app.data.encryptedData = encryptedData;
			//             // app.data.iv = iv;
			//             const data = {
			//               code: codeData.code,
			//               // wxEncryptInfo: {
			//               //   encryptedData: app.trimAll(encryptedData),
			//               //   iv,
			//               // },
			//               memberInfo: {
			//                 avatarUrl: avatarUrl || "",
			//                 city: city || "",
			//                 country: country || "",
			//                 gender: gender || "",
			//                 language: language || "",
			//                 nickName: nickName || "",
			//                 province: province || "",
			//               },
			//               parentInviteCode: uni.getStorageSync("parentInviteCode") || "",
			//             };
			//             //登录接口
			//             const logoData = await getLogin(data);
			//             console.log(logoData, "提交到后端登录接口");
			//             if (logoData.code === 0) {
			//               uni.hideLoading();
			//               uni.showToast({
			//                 title: "登录成功",
			//                 icon: "success",
			//                 duration: 2000,
			//               });
			//               // 获取到的当前数据存入缓存
			//               const { wxToken, openId, userInfo } = logoData.data;
			//               uni.setStorageSync("token", wxToken);
			//               uni.setStorageSync("openId", userInfo.wxOpenid);
			//               uni.setStorageSync("userInfoServer", userInfo);
			//               uni.setStorageSync("phoneNumber", userInfo.phone);
			//               uni.setStorageSync("userId", userInfo.userId);
			//               setTimeout(() => {
			//                 app.handleCancel();
			//               }, 1500);
			//               return true;
			//             } else {
			//               uni.showToast({
			//                 title: "登录失败",
			//                 icon: "success",
			//                 duration: 2000,
			//               });
			//               setTimeout(() => {
			//                 app.handleCancel();
			//               }, 1500);
			//             }
			//           },
			//           fail: (err) => {
			//             console.log(err, "登录错误");
			//           },
			//         });
			//       },
			//       fail() {
			//         console.log("用户拒绝了授权");
			//       },
			//     });
			// },

			// async getPhoneNumber(e) {
			//   console.log(e,'eee')
			//   console.log(e.detail.code, "e 手机code");
			//   const code=await this.getCode()
			//   console.log(code,'登录用得code')
			//   //这里获取code
			//   return;
			//   if (e.detail.code) {
			//     //获取手机号
			//     const getPhoneData = await getPhone(e.detail.code);
			//     if (getPhoneData.code === 0) {
			//       const { phoneNumber } = getPhoneData.data.phone_info;
			//       uni.setStorageSync("phoneNumber", phoneNumber);
			//       uni.showToast({
			//         title: "授权成功",
			//         icon: "success",
			//         duration: 2000,
			//       });
			//       setTimeout(() => {
			//         this.handleCancel();
			//       }, 1500);
			//     } else {
			//       uni.showToast({
			//         title: "授权失败",
			//         icon: "error",
			//         duration: 2000,
			//       });
			//     }
			//   }
			// },

			/**
			 * 暂不登录
			 */
			handleCancel() {
				// 跳转回原页面
				uni.navigateBack({
					delta: 1,
				});
			},

			/**
			 * 登录成功-跳转回原页面
			 */
			// onNavigateBack(delta = 1) {
			//   const pages = getCurrentPages();
			//   if (pages.length > 1) {
			//     uni.navigateBack({
			//       delta: Number(delta || 1),
			//     });
			//   } else {
			//     uni.navigateBack({
			//       delta: 1,
			//     });
			//   }
			// },
		},
	};
</script>

<style lang="scss" scoped>
	.btstyle {
		width: 165rpx;
		background: #0065ff;
		color: white;
	}

	u-checkbox-group::v-deep {
		.u-checkbox__label {
			margin-right: rpx(0);
		}
	}

	.icon-cone {
		margin-right: 10rpx;
	}

	.checkBox_wrapper {
		font-size: rpx(12);
		display: flex;
	}

	.container {
		padding: 0 0rpx;
		font-size: 32rpx;
		background: #fff;
		min-height: 100vh;
		position: relative;
		background: #ffffff;
	}

	.back_img {
		position: absolute;
		top: 80rpx;
		right: 0rpx;
		z-index: 1;

		image {
			width: 350rpx;
		}
	}

	.login-test {
		margin-top: rpx(20);

		display: flex;
		justify-content: center;

		.login-item {
			width: rpx(80);
			height: rpx(80);
			text-align: center;
			margin-left: rpx(20);
			margin-right: rpx(20);

			.login-text {
				width: 100%;
				font-size: rpx(15);
				line-height: rpx(35);
			}

			.logoname-js {
				font-weight: 400;
				font-size: 28rpx;
				color: #A1A1A1;
				line-height: 36rpx;
			}

			.login-icom {

				// width: rpx(48);
				// height: rpx(48);
				// border-radius: 50%;
				// border: rpx(3) solid black;
				// margin: 0 auto;
				.login-icoms {}
			}
		}
	}

	.tsshow {
		font-weight: 500;
		font-size: 26rpx;
		color: #97C1FD;
		line-height: 39rpx;
		padding-top: 39rpx;
		padding-bottom: 56rpx;
		text-align: center;
	}

	.wechatapp {
		//border-bottom: 1rpx solid #e3e3e3;
		// margin-bottom: 72rpx;

		text-align: left;
		width: 100%;
		height: 475rpx;
		overflow: hidden;
		font-weight: 600;
		font-size: 61rpx;
		color: #1B77FB;
		line-height: 78rpx;

		.logoname1 {
			margin-top: 220rpx;
			padding-left: 71rpx;
		}

		.logoname {
			margin-top: 220rpx;
			padding-left: 71rpx;
		}

		.logoname-js {
			font-weight: 400;
			font-size: 28rpx;
			color: #A1A1A1;
			line-height: 36rpx;
			padding-left: 71rpx;
			margin-top: 30rpx;
		}


		.header {
			width: 100%;
			height: 100%;



			.image {
				width: 100%;
				height: 100%;
			}
		}
	}

	.auth-title {
		color: #585858;
		font-size: 60rpx;
		margin-bottom: 40rpx;
		margin-left: 40rpx;
		margin-top: 80rpx;
	}

	.auth-phonetitle {
		color: #585858;
		font-size: 30rpx;
		margin-bottom: 40rpx;
		margin-left: 40rpx;
		line-height: 60rpx;
		margin-top: 80rpx;
	}

	.auth-subtitle {
		color: #888;
		margin-bottom: 88rpx;
		font-size: 60rpx;

	}

	.login-view {
		width: 100%;
		box-sizing: border-box;
		padding: 0 rpx(20);
	}

	.login-btn-qk {
		font-size: 30rpx;
		text-align: center;
		margin-right: 40rpx;
		margin-top: 40rpx;
		font-weight: 500;
		font-size: 28rpx;
		color: #1B77FB;
		line-height: 41rpx;
	}

	.login-btn {
		//padding: 0 20rpx;
		box-sizing: border-box;
		padding: 0 rpx(20);
		margin-bottom: rpx(13);
		margin-top: rpx(13);

		.u-btn-class {
			background: #0065ff !important;
		}

		.button {
			height: 88rpx;
			//background: #04be01;
			color: #fff;
			// background: #0065ff;
			font-size: 30rpx;
			// border-radius: rpx(5);	
			font-weight: bold;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}


	.no-login-btn {
		box-sizing: border-box;
		padding: 0 rpx(20);
		margin-top: 20rpx;
		//padding: 0 20rpx;

		.button {
			height: 88rpx;
			background: #dfdfdf;
			color: #fff;
			font-size: 30rpx;
			// border-radius: rpx(5);
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.item-phone {
		display: flex;
		align-items: center;

	}

	.item-yzm {
		width: 100%;
		display: flex;
		align-items: center;
	}

	.select {
		.index-sss ::v-deep .u-form-item__body {
			background-color: #ffffff;
		}

		::v-deep .u-form-item__body {
			background-color: #EEEEEE;
			border-radius: 50rpx;
			height: 99rpx;
			overflow: hidden;
		}

		::v-deep .u-form-item--left__content__label {
			margin-left: 50rpx;
		}

		::v-deep .u-border-bottom:after {
			border: none;
		}

		::v-deep input:-internal-autofill-selected {
			background-color: none;
		}

		::v-deep .u-flex {
			margin-right: 30rpx;
		}
	}
</style>